package com.cjd.common.preferences

import android.content.Context
import android.content.SharedPreferences
import android.text.TextUtils
import com.cjd.common.utils.GsonUtils

/**
 * @Author chenjidong
 * @email 374122600@qq.com
 * created 2017/7/3
 * description sharePreferences json 存储 不需要 Context
 */
object JsonPreference {
    private val PREFERENCE_NAME = "json_data"
    private var mSharedPreferences: SharedPreferences? = null

    private var editor: SharedPreferences.Editor? = null

    @Synchronized
    fun init(context: Context) {
        mSharedPreferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE)
        mSharedPreferences?.let {
            editor = it.edit()
        }
    }

    fun storeData(key: String, obj: Any?) {
        if (obj == null)
            return

        val data = GsonUtils.instance().toJson(obj)
        editor?.putString(key, data)
        editor?.commit()
    }

    fun isExistData(key: String): Boolean {
        return !TextUtils.isEmpty(mSharedPreferences?.getString(key, ""))
    }

    fun clearData(key: String) {
        editor?.putString(key, "")
        editor?.commit()
    }

    fun clearAll() {
        editor?.clear()?.commit()
    }

    fun <T> extractData(key: String, cls: Class<T>): T? {
        try {
            val jsonStr = mSharedPreferences?.getString(key, null)
            if (!TextUtils.isEmpty(jsonStr))
                return GsonUtils.instance().fromJson(jsonStr, cls)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return null
    }
}